package com.xm.common.aop;

import com.xm.common.annotation.RedisAnnotation;
import com.xm.common.util.ObjectMapperUtil;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.reflect.MethodSignature;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import redis.clients.jedis.JedisCluster;


import java.util.Arrays;


@Component
@Aspect
public class RedisAop {
    @Autowired
    private JedisCluster JedisCluster;

    @Around("@annotation(redis)")
    public Object reidsAround(ProceedingJoinPoint joinpoint, RedisAnnotation redis) throws Throwable {
        String key=redis.key();
        String args= Arrays.toString(joinpoint.getArgs());
        key+="::"+args;
        Object result;
        if(JedisCluster.exists(key)){
            MethodSignature methodSignature=(MethodSignature) joinpoint.getSignature();
            Class resultType=methodSignature.getReturnType();
            String json=JedisCluster.get(key);
            result=ObjectMapperUtil.toObject(json,resultType);
            System.out.println("redis查询");
        }else {
            result=joinpoint.proceed();
            String json=ObjectMapperUtil.toJSON(result);
            if (redis.seconds()>0){
                JedisCluster.setex(key,redis.seconds(),json);
            }else {
                JedisCluster.set(key,json);
            }
            System.out.println("数据库查询");
        }

        return result;

    }
}
